package cm367;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;

@ManagedBean
public class FacilityList {
	private List<Facility> facilitiesList = new ArrayList<Facility>();
	private int facilitiesCount = 0;
	private String dataSeparator = "|";
	private int numFacilityFld = 6;	
	
	public String getDataSeparator() {
		return dataSeparator;
	}

	public void setDataSeparator(String dataSeparator) {
		this.dataSeparator = dataSeparator;
	}

	public FacilityList() throws IOException {
		try {
			ReadWriteDataFile dataFile = new ReadWriteDataFile("db_Facilities.txt");
			String[] facilityRawData = dataFile.ReadDataFile();
			facilitiesCount = facilityRawData.length;
			
			String[] facilityFields = new String[numFacilityFld];
			int idxRow, idxCol;
			int fldIdx;
			String oneLine = "";
			char rdChar; 
			for(idxRow= 0; idxRow < facilitiesCount; idxRow++) {
				oneLine = facilityRawData[idxRow];
				for(idxCol=0; idxCol < numFacilityFld; idxCol++) {
					facilityFields[idxCol] = "";
				}
				fldIdx = 0;
				for(idxCol = 0; idxCol < oneLine.length(); idxCol++) {
					rdChar = oneLine.charAt(idxCol);
					if(dataSeparator.charAt(0) == rdChar) {
						fldIdx++;
					} else {
						if(fldIdx < numFacilityFld) {
							facilityFields[fldIdx] = facilityFields[fldIdx] + rdChar;  
						}
					}
				}
				facilitiesList.add(new Facility(Integer.parseInt(facilityFields[0]), facilityFields[1], facilityFields[2], facilityFields[3], facilityFields[4], Double.parseDouble(facilityFields[5])));
			}
			
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}
	
	public List<Facility> getFacilitiesList() {
		return facilitiesList;
	}

	public void setFacilitiesList(List<Facility> facilitiesList) {
		this.facilitiesList = facilitiesList;
	}

	public int getFacilitiesCount() {
		return facilitiesCount;
	}

	public void setFacilitiesCount(int facilitiesCount) {
		this.facilitiesCount = facilitiesCount;
	}

	public void Write2File(String[] rData) {
		try {
			ReadWriteDataFile dataFile = new ReadWriteDataFile("db_Facilities.txt");
			dataFile.WriteDataFile(rData);
		} catch (IOException e) {
			System.out.println(e.getMessage());
		} 
	}

}
